<template>
  <div class="departments">
    <el-card>
      <template #header> 组织架构 </template>
      <div class="main">
        <TreeItem :itemData="topInfo"> </TreeItem>
        <hr />
        <el-tree :data="treeData">
          <template v-slot="{ data }">
            <TreeItem :itemData="data" @getData='getData'></TreeItem>
          </template>
        </el-tree>
        </div>
    </el-card>



    
     <Add :initData='initData' @getData="getData" ></Add>
  </div>
</template>
<script>
import TreeItem from './components/TreeItem.vue'
import {companyDepartment} from '@/api/departments'
import Add from './components/Add.vue'
export default {
  components: {
    TreeItem,
    Add
  },
   created () {
    this.getData()
  },

 

  data() {
    return {
      topInfo: {
        isTop: true,
        name: '传智教育',
        manager: '负责人',
        id:""
      },
      treeData: [],
      initData:[] //没转换前的组织架构列表数据
    }

  }, 
  created(){
    this.getData()
  },



  methods: {
    async getData () {
      const res = await companyDepartment()
      // 只需要渲染顶级部门
      // this.treeData = res.data.depts
      // 找顶级部门
      this.initData=res.data.depts
      this.treeData = this.changeData(res.data.depts, '')
      console.log('this.treeData', this.treeData)
      // 我要找出财务部子集部门
      // 1：定义一个方法找出数据顶级层数据
      // 2：在找找顶级层过滤条件内找子集层（通过递归调用）

    },
    // 树形数据转换基本转换写法
    changeData (arr, str) {
      // return arr.filter(item => item.pid === str)
      return arr.filter(item => {
        if (item.pid === str) {
          // 使用基本的递归找出子集
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }

}
</script>
<style lang="scss" scoped>
.departments {
  padding: 20px;
  .main {
    width: 100%;
    margin: 0 auto;
  }
}
</style>
